Imports System.Windows.Forms
Imports System.Data.SqlClient
Imports MscHTMenu.clsDefine
Imports SQLUtil.SQL
Imports MscHTMenu.Menu
Imports System.Threading
Public Class frmLogin
    Public Shared sysConn As SqlConnection = Nothing
    Public Shared sysDs As DataSet = Nothing
    Public Shared isLogin As Boolean
    Private comboDVCS As comboData()
    Public frmParent As MscHTMenu.Menu
    Dim starttingDisplay As Boolean
    Dim startingThread As Thread
    Delegate Sub SetValueCallback(ByVal value As Integer)
    Delegate Sub SetCloseCallback()
    Dim oldUserName As String
    Dim bShowKho As Boolean = False

    Private Sub Login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        isLogin = False
        starttingDisplay = False
        If txtName.Enabled = False And txtPassword.Enabled = False And cmdLogin.Enabled = False And cboEntity.Enabled = False And cmdCancel.Enabled = False Then
            starttingDisplay = True
            startingThread = New Thread(AddressOf StartingProBar)
            startingThread.IsBackground = True
            startingThread.Start()
            Return
        End If
        oldUserName = ""
        sysConn = New SqlConnection()
        sysDs = New DataSet()
        sysConn = SQLConnect(MscHTMenu.sConnection)
        If sysConn Is Nothing Then
            MsgBox("Không thể tạo kết nối đến máy chủ, xin vui lòng kiểm tra lại mạng.", MsgBoxStyle.OkOnly, "Quản lý bản hàng")
            Me.txtName.Enabled = False
            Me.cmdLogin.Enabled = False
            Return
        End If
        'Dim strSQL As String        
        'strSQL = "SELECT id, name, 1 as exp FROM tbl_agency"
        'comboDVCS = LoadComBox(sysConn, strSQL, Me.cboEntity)
        'Dim index As Integer

        'If MscHTMenu.sUnitLogin <> "" Then
        '    For index = 0 To comboDVCS.Length - 1
        '        If Trim(comboDVCS(index).id) = Trim(MscHTMenu.sUnitLogin) Then
        '            Me.cboEntity.Text = Trim(comboDVCS(index).id) & " - " & comboDVCS(index).data
        '            Exit For
        '        End If
        '    Next index
        'End If
        txtName.Text = MscHTMenu.sUserLogin
        cboEntity.Enabled = bIsHeadStock
        'Dim y As Integer
        'y = Year(Now())
        'strSQL = "SELECT TOP 1 * FROM cong_no_dau_ky WHERE nam=" & y

        'Dim Rs As New DataSet
        'SQLRetrieve(sysConn, strSQL, "cTable", Rs)
        'If Rs Is Nothing Or Rs.Tables(0).Rows.Count = 0 Then
        '    MsgBox("Dữ liệu đầu kỳ cho năm " & y & " chưa được kết chuyển. Vui lòng liên hệ với người có quyền kết chuyển để kết chuyển dữ liệu đầu kỳ trước khi tiếp tục.", MsgBoxStyle.OkOnly, "Thông báo")
        'End If

        AddHandler txtName.Validated, AddressOf txtName_valid
        AddHandler txtName.Enter, AddressOf txtName_enter
        AddHandler txtName.KeyPress, AddressOf txtKeyPressEnter
        AddHandler txtPassword.KeyPress, AddressOf txtKeyPressEnter
        AddHandler cboEntity.KeyPress, AddressOf txtKeyPressEnter
    End Sub


    Private Sub cmdLogin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdLogin.Click
        Dim strKey As String
        oMenu.bLoggedIn = False
        Dim passEncoded As String = clientManager.EncryptString(txtPassword.Text)
        strKey = "Name = " + ConvertQMC2SQL(Trim(txtName.Text)) + " AND Password = " + ConvertQMC2SQL(Trim(passEncoded))
        Dim cUser = Trim(GetValue(sysConn, "userinfo", "Name", strKey))
        If cUser = "" Then
            ' Sai ten nguoi su dung hoac mat khau
            MsgBox("Sai tên hoặc mật khẩu", MsgBoxStyle.OkOnly, "Đăng nhập")
            txtName.Focus()
            Return
        Else

            Dim ma_dvcs As String = Trim(GetValue(sysConn, "userinfo", "ma_dvcs", strKey))
            Dim ma_dvcs_arr() As String = ma_dvcs.Split(",")

            If Me.cboEntity.SelectedIndex = -1 Then
                MsgBox("Xin vui lòng chọn cửa hàng để đăng nhập", MsgBoxStyle.OkOnly, "Đăng nhập")
                Me.cboEntity.Focus()
                Return
            End If

            Dim i As Integer = 0
            If ma_dvcs_arr.Length > 0 Then
                For i = 0 To ma_dvcs_arr.Length - 1
                    ma_dvcs = Trim(ma_dvcs_arr(i))
                    If ma_dvcs = comboDVCS(Me.cboEntity.SelectedIndex).id Then
                        isLogin = True
                        Exit For
                    End If
                Next
            Else
                isLogin = False
            End If

            If (Not isLogin) And cUser = "ADMIN" Then
                isLogin = True
                ma_dvcs = comboDVCS(Me.cboEntity.SelectedIndex).id
            End If

            If isLogin = True Then
                oMenu.bLoggedIn = True
                Me.Close()
                clientManager.Config.User = clientManager.EncryptString(Trim(cUser))
                clientManager.Config.Dvcs_Code = Trim(ma_dvcs)
                clientManager.Config.LoginTime = GetCurrentDateTime()
                clientManager.SaveConfiguration(sConfigurationFile)
                If String.Compare(sUserLogin, txtName.Text.Trim) <> 0 Then
                    sUserLogin = txtName.Text.Trim
                    oMenu.explorer.RemoveObject()
                    oMenu.ShowMenu()
                End If                
            Else
                MsgBox("Cửa hàng không đúng, vui lòng chọn lại", MsgBoxStyle.OkOnly, "Đăng nhập")
                Me.cboEntity.Focus()
                Return
            End If
        End If
    End Sub

    Private Sub frmLogin_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Closed
        sysDs = Nothing
        startingThreadStop = True

        If Not (sysConn Is Nothing) Then
            sysConn.Close()
        End If
        If isLogin = False And starttingDisplay = False Then
            frmMenu.Close()
        End If
    End Sub

    Private Sub cmdCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCancel.Click
        Me.Close()
    End Sub

    Private Sub txtName_enter(ByVal sender As Object, ByVal e As System.EventArgs)
        oldUserName = Trim(sender.Text)
    End Sub

    Private Sub txtName_valid(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim newValue As String = Trim(sender.Text)
        If oldUserName = newValue And bShowKho Then Return
        'Get dvcs and add to combo box
        Dim strSQL As String
        If newValue <> "ADMIN" Then
            'Get cua hang list cho user
            Dim cMa_dvcs = Trim(GetValue(sysConn, "userinfo", "ma_dvcs", "name='" + newValue + "'"))
            Dim maDvcsList As String() = cMa_dvcs.Split(New Char() {","c})
            Dim inList As String = String.Empty
            Dim i As Integer = 0
            Dim len As Integer = maDvcsList.Length - 1
            For i = 0 To len - 1
                inList = inList + "'" + Trim(maDvcsList(i)) + "',"
            Next
            inList = inList + "'" + Trim(maDvcsList(len)) + "'"
            inList = "(" + inList + ")"

            strSQL = "SELECT id, name, 1 as exp FROM tbl_agency WHERE id IN " + inList
        Else
            strSQL = "SELECT id, name, 1 as exp FROM tbl_agency"
        End If

        comboDVCS = LoadComBox(sysConn, strSQL, Me.cboEntity)

        If comboDVCS.Length > 0 Then
            Me.cboEntity.SelectedIndex = 0
        End If
        Dim index As Integer
        If MscHTMenu.sUnitLogin <> "" Then
            For index = 0 To comboDVCS.Length - 1
                If Trim(comboDVCS(index).id) = Trim(MscHTMenu.sUnitLogin) Then
                    Me.cboEntity.Text = Trim(comboDVCS(index).id) & " - " & comboDVCS(index).data
                    Exit For
                End If
            Next index
        End If

        If comboDVCS.Length > 1 Then
            cboEntity.Visible = True
            lblEntity.Visible = True
            bShowKho = True
        Else            
            cboEntity.Visible = False
            lblEntity.Visible = False
        End If
    End Sub

    Public Sub txtKeyPressEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If AscW(e.KeyChar) = 13 Then
            SendKeys.Send("{Tab}")
        End If
    End Sub

    Public Sub UpdateProgressBar(ByVal value As Integer)
        Me.UpdateProgressProcess(value)
    End Sub

    Public Sub UpdateProgressProcess(ByVal value As Integer)
        Try
            If Not startingThreadStop Then
                If value > proBarKN.Maximum Then
                    value = proBarKN.Maximum
                End If
                If Me.proBarKN.InvokeRequired Then
                    Dim d As New SetValueCallback(AddressOf UpdateProgressBar)
                    Me.Invoke(d, New Object() {value})
                Else
                    proBarKN.Value = value
                End If
            End If
        Catch ex As Exception
        End Try
    End Sub
    Private Sub StartingProBar()
        Dim i As Integer = proBarKN.Maximum
        While (Not startingThreadStop)
            UpdateProgressBar(i)
            i = i + 1
            If i > proBarKN.Maximum Then
                i = 0
            End If
            Thread.Sleep(10)
        End While
        startingThread = Nothing
        If Me.InvokeRequired Then
            Dim d As New SetCloseCallback(AddressOf StartingProBar)
            Me.Invoke(d, New Object() {})
        Else
            Me.Close()
        End If
    End Sub

End Class
